package com.cskaoyan.batch;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

// 批处理的Demo
public class BatchDemo {

    public static void main(String[] args) {

        long startTime = System.currentTimeMillis();

        forDeal();
        long t1 = System.currentTimeMillis();


        statementBatch();
        long t2 = System.currentTimeMillis();


        prepareStatementBatch();
        long t3 = System.currentTimeMillis();


        System.out.println("for循环的时间：" + (t1-startTime)+ " 毫秒");
        System.out.println("statement的时间：" + (t2-t1)+ " 毫秒");
        System.out.println("prepareStatement：" + (t3-t2)+ " 毫秒");

    }


    // for 循环
    public static void forDeal(){

        try {
            // 获取连接
            Connection connection = JDBCUtils.getConnection();

            // 获取statement
            Statement statement = connection.createStatement();


            for (int i = 0; i < 1000; i++) {

                // 执行sql语句
                statement.executeUpdate("insert into user values (null,'zhangsan','zhangsan',20)");
            }


            // 关闭资源
            JDBCUtils.closeSource(connection,statement,null);

        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    // statement
    public static void statementBatch(){

        try {
            // 获取连接
            Connection connection = JDBCUtils.getConnection();

            // 获取statement
            Statement statement = connection.createStatement();

            // 使用 statement批处理
            for (int i = 0; i < 1000; i++) {

                statement.addBatch("insert into user values (null,'张飞','俺也一样',40)");
            }
            // 每一个SQL语句影响的行数封装成了一个数组
            int[] ints = statement.executeBatch();


            // 关闭资源
            JDBCUtils.closeSource(connection,statement,null);

        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    // PrepareStatement 的批处理
    public static void prepareStatementBatch() {

        try {

            // 获取连接
            Connection connection = JDBCUtils.getConnection();

            // 获取PrepareStatement对象
            PreparedStatement preparedStatement = connection.prepareStatement("insert into user values (null,?,?,?)");


            for (int i = 0; i < 1000; i++) {


                preparedStatement.setString(1,"兰钊");
                preparedStatement.setString(2,"我的心里只有工作");
                preparedStatement.setInt(3,40);

                // 添加到batch
                preparedStatement.addBatch();
            }

            // 执行sql  返回的还是影响的行数
            int[] ints = preparedStatement.executeBatch();

            // 关闭资源
            JDBCUtils.closeSource(connection,preparedStatement,null);


        }catch (Exception ex) {

        }

    }
}
